package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeptMapper;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserServicel;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserServicel {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private DeptMapper deptMapper;

    private boolean isLowestDept(String deptNo) {
        int count = deptMapper.isLowestDept(deptNo);
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 添加
     * @param userDto
     */

    @Override
    public void adduser(UserDto userDto) {

        if (isLowestDept(userDto.getDeptNo())) {
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }
        User user = BeanUtil.toBean(userDto, User.class);
        //设置默认用户名 默认为邮箱
        user.setUsername(user.getEmail());
        //设置默认昵称为真实姓名
        user.setNickName(user.getRealName());
        user.setDataState(SuperConstant.DATA_STATE_0);
        //TODO 需要设置默认，并且需要加密
        String password = "itcast";
        user.setPassword(password);
        //添加用户信息
        int flag = userMapper.insert(user);
        if (flag == 0) {
            throw new RuntimeException("保存用户信息出错");
        }
        //保存用户角色中间表
        //新建一个集合，保存用户角色中间表信息
        List<UserRole> userRoles = Lists.newArrayList();
        userDto.getRoleVoIds().forEach(r -> {
            userRoles.add(UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(r))
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build());
        });
        flag = userRoleMapper.batchInsert(userRoles);
        if (flag == 0) {
            throw new RuntimeException("保存用户角色中间表出错");
        }

    }

    /**
     * 分页
     * @param userDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResponse<UserVo> findUserPage(UserDto userDto, Integer pageNum, Integer pageSize) {
        //1.判断是否有值
        if(!EmptyUtil.isNullOrEmpty(userDto.getDeptNo())){
            //有值进行截取 把截取后的值设置给userDto
            userDto.setDeptNo(NoProcessing.processString(userDto.getDeptNo()));
        }
        //2.开启分页
        PageHelper.startPage(pageNum,pageSize);
        //查询数据
        Page<List<User>> lists = userMapper.selectPage(userDto);
        PageResponse<UserVo> pageResponse = PageResponse.of(lists, UserVo.class);
        return pageResponse;
    }

    /**
     * 获取用户列表
     * @param userDto
     * @return
     */
    @Override
    public List<UserVo> getlistuser(UserDto userDto) {
        List<User> userlist = userMapper.selectList();
        return BeanUtil.copyToList(userlist,UserVo.class);
    }

    /**
     * 修改
     * @param userDto
     * @return
     */
    @Override
    public Boolean updateUser(UserDto userDto) {
        //根据部门编号查询，是否是最底层的部门，如果不是，不允许添加用户
        if (isLowestDept(userDto.getDeptNo())) {
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }
        //转换UserVo为User
        User user = BeanUtil.toBean(userDto, User.class);
        user.setUsername(userDto.getEmail());
        int flag = userMapper.updateByPrimaryKeySelective(user);
        if (flag == 0) {
            throw new RuntimeException("修改用户信息出错");
        }
        if (CollUtil.isNotEmpty(userDto.getRoleVoIds())) {
            //删除角色中间表
            boolean flagDel = userRoleMapper.deleteUserRoleByUserId(user.getId());
            if (!flagDel) {
                throw new RuntimeException("删除角色中间表出错");
            }

            //重新保存角色中间表
            List<UserRole> userRoles = Lists.newArrayList();
            userDto.getRoleVoIds().forEach(r -> {
                userRoles.add(UserRole.builder()
                        .userId(user.getId())
                        .roleId(Long.valueOf(r))
                        .dataState(SuperConstant.DATA_STATE_0)
                        .build());
            });
            flag = userRoleMapper.batchInsert(userRoles);
            if (flag == 0) {
                throw new RuntimeException("保存角色中间表出错");
            }
        }

        return true;
    }

    /**
     * 删除
     * @param userId
     * @return
     */
    @Override
    public Object deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位关联
        return userMapper.deleteByPrimaryKey(userId);
    }

    /**
     * 启用禁用
     * @param id
     * @param status
     */
    @Override
    public void isEnable(Long id, String status) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) {
            throw new BaseException(BasicEnum.USER_EMPTY_EXCEPTION);
        }
        user.setDataState(status);
        userMapper.updateByPrimaryKeySelective(user);
    }
}
